package com.zhourh.bang.modular.edu.controller;

import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.zhourh.bang.common.controller.BaseController;
import com.zhourh.bang.common.exception.BizExceptionEnum;
import com.zhourh.bang.common.exception.BussinessException;
import com.zhourh.bang.common.persistence.dao.SScoreMapper;
import com.zhourh.bang.common.persistence.dao.SSubjectMapper;
import com.zhourh.bang.common.persistence.model.SScore;
import com.zhourh.bang.common.persistence.model.SSubject;
import com.zhourh.bang.common.support.Response;
import com.zhourh.bang.core.util.ToolUtil;
import com.zhourh.bang.modular.edu.dao.SubjectDao;
import com.zhourh.bang.modular.edu.service.ISubjectService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * 课程控制器
 *
 * @author fengshuonan
 * @Date 2018-06-22 10:53:56
 */
@Controller
@RequestMapping("/subject")
public class SubjectController extends BaseController {

    private String PREFIX = "/edu/subject/";

    @Resource
    private SSubjectMapper subjectMapper;

    @Resource
    private SScoreMapper sScoreMapper;

    @Resource
    private SubjectDao subjectDao;

    @Resource
    private ISubjectService subjectService;

    /**
     * 跳转到课程首页
     */
    @RequestMapping("")
    public String index() {
        return PREFIX + "subject.html";
    }

    /**
     * 跳转到添加课程
     */
    @RequestMapping("/subject_add")
    public String subjectAdd() {
        return PREFIX + "subject_add.html";
    }

    /**
     * 跳转到修改课程
     */
    @RequestMapping("/subject_update/{subjectId}")
    public String subjectUpdate(@PathVariable Integer subjectId, Model model) {
        return PREFIX + "subject_edit.html";
    }

    /**
     * 获取课程列表
     */
    @RequestMapping(value = "/list")
    @ResponseBody
    public Object list(String key) {
        return this.subjectDao.list(key);
    }

    /**
     * 新增课程
     */
    @RequestMapping(value = "/add")
    @ResponseBody
    public Object add(SSubject subject) {
        if (ToolUtil.isOneEmpty(subject, subject.getName(), subject.getCode())) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        subject.insert();
        return super.SUCCESS_TIP;
    }

    /**
     * 删除课程
     */
    @RequestMapping(value = "/delete")
    @ResponseBody
    public Object delete(Integer subjectId) {
        return subjectMapper.deleteById(subjectId);
    }


    /**
     * 修改课程
     */
    @RequestMapping(value = "/update")
    @ResponseBody
    public Object update(SSubject subject) {
        if (ToolUtil.isOneEmpty(subject, subject.getName(), subject.getCode())) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        this.subjectMapper.updateById(subject);
        return super.SUCCESS_TIP;
    }

    /**
     * 课程详情
     */
    @RequestMapping(value = "/detail")
    @ResponseBody
    public Object detail(Integer subjectId) {
        return this.subjectMapper.selectById(subjectId);
    }

    /**
     * 上传课程列表
     */
    @RequestMapping(value = "upload")
    @ResponseBody
    public Object upload(MultipartFile file) {
        System.out.println(file.getName());
        System.out.println(file.getSize());
        System.out.println(file.getOriginalFilename());
        int count = 0;
        try {
            ExcelReader reader = ExcelUtil.getReader(file.getInputStream());
            List<SSubject> studentList = reader.readAll(SSubject.class);
            if (studentList != null && !studentList.isEmpty()) {
                for (SSubject subject : studentList) {
                    if (subject.insert()) {
                        count++;
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return count;
    }

    /**
     * 跳转到分数统计
     */
    @RequestMapping("toStat")
    public String toStat(String id, Model model) {
        model.addAttribute("id", id);
        return PREFIX + "stat.html";
    }

    /**
     * 根据subject id，计算平均分等结果
     */
    @RequestMapping("getStatById")
    @ResponseBody
    public Response getStatById(String id) {
        if (StrUtil.isNotEmpty(id)) {
            Response response = Response.success();
            Wrapper<SScore> wrapper = new EntityWrapper<>();
            wrapper.eq("subjectId", id);
            List<SScore> scoreList = sScoreMapper.selectList(wrapper);
            if (scoreList != null && scoreList.size() > 0) {
                ArrayList<Double> arr = new ArrayList<>();
                Double total = 0.0;
                Double max = 0.0;
                Double min = 100.0;
                int num4a = 0, num4b = 0, num4c = 0, num4d = 0;
                for (SScore score : scoreList) {
                    if (score.getScore() != null && score.getScore() >= 0) {
                        total += score.getScore();
                        arr.add(score.getScore());
                        if (max < score.getScore()) {
                            max = score.getScore();
                        }
                        if (min > score.getScore()) {
                            min = score.getScore();
                        }
                        //90
                        if(score.getScore()>=90){
                            num4a++;
                        }
                        if(score.getScore()>=80){
                            num4b++;
                        }
                        if(score.getScore()>=70){
                            num4c++;
                        }
                        if(score.getScore()>=60){
                            num4d++;
                        }
                    }
                }
                DecimalFormat df = new DecimalFormat("0.00");
                Double avg = total / scoreList.size();
                int over = 0;
                for(SScore score : scoreList){
                    if(score!=null && score.getScore()>=avg){
                        over++;
                    }
                }
                response.put("avg", df.format(avg));//平均值
                response.put("rate4over", df.format((float)over/scoreList.size()));//超均率
                response.put("max", max);//最大值
                response.put("min", min);//最小值
                //计算标准差
                int total4bjc=0;
                for(SScore score : scoreList){
                    if(score!=null && score.getScore()>=0){
                        total4bjc += (score.getScore()-avg)*(score.getScore()-avg);   //求出方差，如果要计算方差的话这一步就可以了
                    }
                }
                response.put("standard",df.format(Math.sqrt(total4bjc/scoreList.size())));//方差（标准差）
                response.put("rate4b",df.format((float)num4b/scoreList.size()));//优良率
                response.put("rate4d",df.format((float)num4d/scoreList.size()));//及格率
            }
            return response;
        }
        return Response.success();
    }
}
